#!/usr/bin/env python
# Python Comic Book Displayer Aka PyCDisplay
# Made by: CodedNinja
# Copyright (c) 2009 CodedNinja. All rights reserved.
# Project site: http://code.google.com/p/pycdisplay/
# Version Number = 0.0.1
# Zip files only
# 
# Features that needs work...
#  Tell if it is a ZipFile, TarFile, RarFile
#  RarFile needs to be made from scratch
#  Gui file open needs to be made from scratch
#  Menu bar needs to be made from scratch
#  Comment the source Code out
#
#
#
#
import os
import platform
import pygame
from pygame.locals import *
import minimize
import zipfile

if (platform.system() == "Windows") or (platform.system() == "Darwin"):
    import EasyDialogs
    fileopen = 1
else:
    fileopen = 0

def main():
    
    pygame.init()
    
    # Variables that control the main loop
    running = True
    fullscreen = 1
    down = 0
    window_size = (600, 600)
    default_size = (600, 600)
    image_axis = (0, 0)
    
    # load and set the logo
    logo = pygame.image.load("mainicon.png")
    pygame.display.set_icon(logo)
    pygame.display.set_caption("PyCDisplay")
    screen = pygame.display.set_mode(window_size, RESIZABLE)
    
    if fileopen == 1:
        file = EasyDialogs.AskFileForOpen()
    else:
        file = raw_input('File name: ')
    images = unzip_file_into_dir(file, "tmp")
    if images != False:
        back_file = images[0]
        current_file = images[0]
        next_file = images[1]
        back_page_number = -1
        page_number = 0
        next_page_number = 1
        max_page = len(images)
        load_image(current_file, window_size, image_axis[1], screen)

    for maxsize in pygame.display.list_modes():
        if pygame.display.mode_ok(maxsize):
            maxsize = maxsize
            break
    # blit image to screen
    # update the screen to make the changes visible (fullscreen update)
    pygame.display.flip()
    # main loop
    while running:
        # event handling, gets all event from the eventqueue
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                Close()
                running = False
            elif event.type == KEYDOWN:
                # If w key is pressed
                if (event.key == K_w):
                    if images != False:
                        if fullscreen == 1:
                            screen = pygame.display.set_mode(maxsize, FULLSCREEN)
                            load_image(current_file, maxsize, image_axis[1], screen)
                            fullscreen = 0
                            down = 0
                            window_size = maxsize
                        else:
                            screen = pygame.display.set_mode(default_size, RESIZABLE)
                            window_size = default_size
                            load_image(current_file, window_size, image_axis[1], screen)
                            fullscreen = 1
                            down = 0
                # If ESC key is pressed
                elif (event.key == K_ESCAPE):
                    Close(images)
                    running = False
                # If o key is pressed Aka Open file
                elif (event.key == K_o):
                    file = EasyDialogs.AskFileForOpen()
                    images = unzip_file_into_dir(file, "tmp")
                # If m key is pressed
                elif (event.key == K_m):
                    if (platform.system() == "Windows"):
                        minimize.minimize()
                    else:
                        if (platform.system() == "Darwin"):
                            EasyDialogs.Message("Sorry only minimize works on windows for now.")
                        else:
                            print "Sorry only minimize works on windows for now."
                # If Right arrow key is pressed
                elif (event.key == K_RIGHT):
                    if images != False:
                        if next_page_number == max_page:
                            next_page_number =  max_page
                        else:
                            back_page_number += 1
                            back_file = images[back_page_number]
                            page_number += 1
                            current_file = images[page_number]
                            if fullscreen == 1:
                                image_axis = (0,0)
                                load_image(next_file, window_size, image_axis[1], screen)
                                down = 0
                            else:
                                image_axis = (0,0)
                                load_image(next_file, maxsize, image_axis[1], screen)
                                down = 0
                            next_page_number += 1
                            if next_page_number == max_page:
                                next_page_number =  max_page
                            else:
                                next_file = images[next_page_number]
                # If Left arrow key is pressed
                elif (event.key == K_LEFT):
                    if images != False:
                        if  0 >= page_number:
                            page_number = 0
                        else:
                            next_page_number -= 1
                            next_file = images[next_page_number]
                            page_number -= 1
                            current_file = images[page_number]
                            back_page_number -= 1
                            if fullscreen == 1:
                                image_axis = (0,0)
                                load_image(back_file, window_size, image_axis[1], screen)
                                down = 0
                            else:
                                back_file = images[0]
                                current_file = images[0]
                                next_file = images[1]
                                page_number += 0
                                image_axis = (0,0)
                                load_image(back_file, maxsize, image_axis[1], screen)
                                down = 0
                            if 0 >= page_number:
                                page_number = 0
                            else:
                                back_file = images[back_page_number]
                # If Up arrow key is pressed
                elif (event.key == K_UP):
                    if images != False:
                        image = pygame.image.load(current_file).convert()
                        images_height = pygame.Surface.get_height(image)
                        if images_height >= window_size[1]:
                            if 0 == down:
                                work = 1
                            else:
                                height_differents = images_height - window_size[1]
                                height_differents = height_differents / 2
                                image_axis = (image_axis[0], image_axis[1] + height_differents)
                                load_image(current_file, window_size, image_axis[1], screen)
                                down -= 1
                elif (event.key == K_DOWN):
                    if images != False:
                        image = pygame.image.load(current_file).convert()
                        images_height = pygame.Surface.get_height(image)
                        if images_height >= window_size[1]:
                            if down >= 2:
                                work = 1
                            else:
                                height_differents = images_height - window_size[1]
                                height_differents = height_differents / 2
                                image_axis = (image_axis[0], image_axis[1] - height_differents)
                                load_image(current_file, window_size, image_axis[1], screen)
                                down += 1
            # Update the image with window resize
            elif event.type == pygame.VIDEORESIZE:
                window_size = event.size
                screen = pygame.display.set_mode(window_size, RESIZABLE)
                load_image(current_file, event.size, 0, screen)

# Find out right X value from top left of the window
def image_x(image, maxsize):
    image_width = pygame.Surface.get_width(image)
    image_x = int(maxsize[0])
    if (image_width >= image_x):
        return 0
    else:
        image_x = image_x - image_width
        image_x = image_x / 2
        return image_x

# Load the image
def load_image(file_image, size_image, image_y, screen):
    image = pygame.image.load(file_image).convert()
    images_height = pygame.Surface.get_height(image)
    images_width = pygame.Surface.get_width(image)
    images_x = image_x(image, size_image)
    if (images_width >= size_image[0]):
        images_width = size_image[0]
    else:
        images_width = images_width
    image = pygame.transform.scale(image, (images_width, images_height))
    screen.blit(image, (images_x, image_y))
    pygame.display.flip()
    return 0

# Unzip the achive to a dir
def unzip_file_into_dir(file, dir):
    iszip = zipfile.is_zipfile(file)
    if iszip == True:
        zfobj = zipfile.ZipFile(file)
        images = []
        for name in zfobj.namelist():
            if name.endswith('/'):
                os.mkdir(os.path.join(dir, name))
            else:
                if name.endswith(".jpg") | name.endswith(".jpeg") | name.endswith(".png"):
                    outfile = open(os.path.join(dir, name), 'wb')
                    outfile.write(zfobj.read(name))
                    outfile.close()
        listdir = os.listdir(dir)
        for image in listdir:
            images.append(dir + "/" + image)
        return images
    return False
    
# Delete all images in tmp folder
def Close(images):
    for image in images:
        os.remove(image)

if __name__=="__main__":
    main()